//
//  YWSelectEquTypeMultiTVC.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/5/11.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWSelectEquTypeMultiTVC.h"
#import "YWReportTroubleSubscriptionTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"

#import "YWEquipmentType.h"
#import "YWEquipmentManager.h"

@interface YWSelectEquTypeMultiTVC ()
<UISearchResultsUpdating,UISearchControllerDelegate>{
    NSIndexPath *lastIndexPath;
}
@property (nonatomic, strong) NSMutableArray *allEquipmentTypes;
@property (nonatomic, strong) NSArray *equipmentSubSystemArray;
@property (nonatomic, strong) NSMutableArray * didSelEquTypeArray;
//搜索的结果数据
@property (nonatomic, strong) NSMutableArray  *searchList;
//搜索的控制器
@property (nonatomic, strong) UISearchController *searchController;
@end

@implementation YWSelectEquTypeMultiTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"选择设备类型";
    [self initTableView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 44.0f;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    _searchController.delegate = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    [_searchController.searchBar sizeToFit];
    
    UIColor *color =  [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];
    _searchController.searchBar.layer.borderWidth = 1;
    _searchController.searchBar.layer.borderColor = [color CGColor];
    _searchController.searchBar.barTintColor = color;
    self.tableView.tableHeaderView = _searchController.searchBar;
    
    [self.tableView setEditing:YES];
}

- (NSArray *)equipmentSubSystemArray{
    if (!_equipmentSubSystemArray) {
        _allEquipmentTypes = [NSMutableArray array];
        _equipmentSubSystemArray = [[NSArray alloc] initWithArray:[[YWEquipmentManager shareManager] allEquipmentTypeWithSystemId:self.sysTemType.systemTypeId]];
        [_equipmentSubSystemArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [_allEquipmentTypes addObjectsFromArray:obj];
        }];
    }
    return _equipmentSubSystemArray;
}

//-(void)setOwnEquipmentType:(YWEquipmentType *)ownEquipmentType{
//    _ownEquipmentType = ownEquipmentType;
//    if (ownEquipmentType) {
//        [self.allEquipmentTypes enumerateObjectsUsingBlock:^(YWEquipmentType*  _Nonnull equipmentType, NSUInteger idx, BOOL * _Nonnull stop) {
//            if (equipmentType.equipmentTypeId == ownEquipmentType.equipmentTypeId) {
//                selectedEquipmentType = equipmentType;
//            }
//        }];
//    }
//}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _searchController.active ? 1: self.equipmentSubSystemArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _searchController.active ? [self.searchList count] :[self.equipmentSubSystemArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"selectDepartmentTableVCReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.textLabel.font = kContentFont;
    }
    if (_searchController.active) {
        YWEquipmentType *equipmentType = self.searchList[indexPath.row];
        cell.textLabel.text = equipmentType.equipmentTypeName?:@"";
    }else{
        YWEquipmentType *equipmentType = self.equipmentSubSystemArray[indexPath.section][indexPath.row];
        cell.textLabel.text = equipmentType.equipmentTypeName?:@"";
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    YWEquipmentType *equipmentType = _searchController.active ? self.searchList[indexPath.row] : self.equipmentSubSystemArray[indexPath.section][indexPath.row];
    [self.didSelEquTypeArray enumerateObjectsUsingBlock:^(YWEquipmentType *     _Nonnull equType, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %d", @"equipmentTypeId", equipmentType.equipmentTypeId];
        NSArray *array = [[self.didSelEquTypeArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count>0) {
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
            *stop = YES;
        }else{
            [tableView deselectRowAtIndexPath:indexPath animated:NO];
        }
    }];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (_searchController.active) {
        return nil;
    }else{
        YWEquipmentType *equipmentType = self.equipmentSubSystemArray[section][0];
        YWEquipmentSubSystemType *subSystem = equipmentType.equipmentSubSystemType;
        return subSystem.subSystemTypeName?:@"";
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWEquipmentType *equipmentType = _searchController.active ? self.searchList[indexPath.row] : self.equipmentSubSystemArray[indexPath.section][indexPath.row];
    if (![self.didSelEquTypeArray containsObject:equipmentType]) {
        [self.didSelEquTypeArray addObject:equipmentType];
    }
    if (lastIndexPath) {
        [tableView deselectRowAtIndexPath:lastIndexPath animated:NO];
    }
    [self.tableView reloadData];
    lastIndexPath = indexPath;
    if (_searchController.active) {
        [_searchController setActive:NO];
        [self rightBarButtonItemEvent:nil];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWEquipmentType *equipmentType = _searchController.active ? self.searchList[indexPath.row] : self.equipmentSubSystemArray[indexPath.section][indexPath.row];
    [self.didSelEquTypeArray enumerateObjectsUsingBlock:^(YWEquipmentType *     _Nonnull equType, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %d", @"equipmentTypeId", equipmentType.equipmentTypeId];
        NSArray *array = [[self.didSelEquTypeArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count>0) {
            [self.didSelEquTypeArray removeObjectsInArray:array];
            *stop = YES;
        }
    }];
//    if (equipmentType.equipmentTypeId == selectedEquipmentType.equipmentTypeId) {
//        selectedEquipmentType = nil;
//    }
    lastIndexPath = nil;
}

- (void)rightBarButtonItemEvent:(id)sender{
    if (self.didSelEquTypeArray.count>0) {
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithObject:self.didSelEquTypeArray forKey:@"didSelEquTypeArray"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kselectEqumentTypeNoti" object:nil userInfo:dic];
        
        UIViewController *vc = nil;
        for (UIViewController *temp in self.navigationController.viewControllers) {
            if ([temp isKindOfClass:[YWReportTroubleSubscriptionTableViewController class]]) {
                vc = temp;
                break;
            }
        }
        if (vc) {
            [self.navigationController popToViewController:vc animated:YES];
        }

//        if ([self.delegate respondsToSelector:@selector(popSelectedEquTypeArrayFromMultiVC:)]) {
//            [self.delegate popSelectedEquTypeArrayFromMultiVC:self.didSelEquTypeArray];
//            [self.navigationController popViewControllerAnimated:YES];
//        }
    }else{
        [YWCommonTool showTextHUDWithContent:@"请选择一个设备类型"];
    }
}

- (NSMutableArray*)didSelEquTypeArray{
    if (!_didSelEquTypeArray) {
        _didSelEquTypeArray = [NSMutableArray array];
        [_didSelEquTypeArray addObjectsFromArray:self.haveSelEquTypeArray];
    }
    return _didSelEquTypeArray;
}

//搜索时过滤数据
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString = searchController.searchBar.text;
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K CONTAINS %@", @"equipmentTypeName", searchString];
    
    if (self.searchList!= nil) {
        [self.searchList removeAllObjects];
    }
    self.searchList = [[self.allEquipmentTypes filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    [self.tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = YES;
}

- (void)willDismissSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = NO;
}

- (void)dealloc{
    [_searchController.view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
